<?php

namespace Home\Controller;

use Utuo\ForegroundController;

class MicroSeckillController extends ForegroundController {
	
	private $micSeckill;
	public function _init() {
		layout ( false );
		C('TOKEN_ON',false);
		$this->setModelName();
		$this->micSeckill = M ( 'MicroSeckill' )->where ( 'cid='.$this->sid.' and UNIX_TIMESTAMP(start_time)>=' . time () )->order ( 'start_time asc' )->find ();
	    $this->id=$this->micSeckill['id'];
	}
	public function indexAction($sid) {
	$this->assign("microSeckill",$this->micSeckill);
	 $this->display();
		
	}
	public function saveAction(){
		$tel=I('tel');
		$this->checkExpire();
		$isApply = $this->isApply($tel);
		if ($isApply === false) {
			$this->ajaxError ( '亲~网络有点忙，请再试一次吧！' );
		} else if(empty($isApply)){
			$m=D('MicroSeckillApply');
			if($m->create())
			{
				$m->apply_time=time();
				$m->cid=$this->sid;
				$id=$m->add();
				$this->checkId($id);
			}else{
				$this->ajaxError($m->getError());
			}
		}else{
			if($isApply['is_error'] == 1){
				$this->ajaxError ( '亲~您已经参与过了哟！' );
			}
			$this->ajaxError ( '亲,可不要贪多哟！' );
		}
	}
	private function checkExpire(){
		$now = time();
		if ( $now < $this->micSeckill['start_time']) {
			$this->ajaxError ( '亲，活动还未开始，再等一会哦！' );
		} elseif( $now > $this->micSeckill['end_time']) {
			$this->ajaxError ( '亲，活动已经结束，下次早点来哦！' );
		}
	}
	private function checkId($id){
		if($id === false){
			$this->ajaxError ( '亲~网络有点忙，请再试一次吧！' );
		} else {
			if ($this->getApplyCount ( $id ) >= $this->micSeckill['daily_number']) {
				D ( 'MicroSeckillApply' )->where("id=%d",$id)->save(array('is_error'=>1));//超过人数后设置is_error=1表示为未成功
				$this->ajaxError ( '哎呀，太遗憾了！下次要早点来哦！' );
			} else {
				$this->ajaxSuccess ( '恭喜你秒杀成功啦！我们工作人员会尽快与您联系送货。' );
			}
		}
	}
	private function isApply($tel) {
		return M ( 'MicroSeckillApply' )->where ( array(
				"tel" => $tel,
				"cid" => $this->sid,
				'micro_seckill_id'=>$this->micSeckill['id']
		))->find ();
	}
   private function getApplyCount($id) {
		$condation=array(
			'cid'=>$this->sid,
			'micro_seckill_id'=>$this->micSeckill['id']
		);
		$condation['id']=array(array('LT',$id));
		$count = M ( 'MicroSeckillApply' )->where ( $condation )->count ();
		return $count;
	}
}